package com.hs.srm.admin.modules.notice.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hs.srm.admin.modules.notice.dao.NoticeDefinitionManageDao;
import com.hs.srm.admin.modules.notice.entity.NoticeDefinitionManageEntity;
import com.hs.srm.admin.modules.notice.entity.NoticeRoleEntity;
import com.hs.srm.admin.modules.notice.service.NoticeDefinitionManageService;
import com.hs.srm.admin.modules.notice.service.NoticeRoleService;
import com.hs.srm.base.common.utils.QueryParam;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 通知定义管理
 *
 * @author ych
 * @since 2020-04-02 10:15:44
 */
@Service("noticeDefinitionManageService")
public class NoticeDefinitionManageServiceImpl extends ServiceImpl<NoticeDefinitionManageDao, NoticeDefinitionManageEntity> implements NoticeDefinitionManageService {

    @Autowired
    private NoticeDefinitionManageDao noticeDefinitionManageDao;

    @Autowired
    private NoticeRoleService noticeRoleService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        //通知类型
        String kind = (String) params.get("kind");

        Page page = this.selectPage(new QueryParam<NoticeDefinitionManageEntity>(params).getPage(),
                new EntityWrapper<NoticeDefinitionManageEntity>()
                        .eq(StringUtils.isNotBlank(kind), "kind", kind)
        );

        return new PageUtils(page);
    }

    /**
     * 保存通知定义
     *
     * @param noticeDefinitionEntity
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R saveDefinition(NoticeDefinitionManageEntity noticeDefinitionEntity) {
        //创建日期
        noticeDefinitionEntity.setCreateDate(new Date());
        //保存新建或更新的通知类型
        this.insertOrUpdate(noticeDefinitionEntity);

        //通过通知类型id删除通知类型与角色关联的数据
        Map<String, Object> columnMap = new HashMap<>(1);
        columnMap.put("notice_id", noticeDefinitionEntity.getPkId());
        noticeRoleService.deleteByMap(columnMap);

        //通知类型关联角色
        List<Integer> roleList = noticeDefinitionEntity.getRoleList();
        List<NoticeRoleEntity> noticeRoleEntityList = new ArrayList<>();
        NoticeRoleEntity entity;
        for (Integer item : roleList) {
            entity = new NoticeRoleEntity();
            entity.setNoticeId(noticeDefinitionEntity.getPkId());
            entity.setRoleId(item);
            noticeRoleEntityList.add(entity);
        }
        noticeRoleService.insertBatch(noticeRoleEntityList);

        return R.ok();
    }
}